package com.xuecheng.media.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.xuecheng.api.media.AliyunVoApi;
import com.xuecheng.api.media.model.aliyun.VodUploadRequest;
import com.xuecheng.api.media.model.aliyun.VodUploadToken;
import com.xuecheng.common.exception.ExceptionCast;
import com.xuecheng.media.common.constant.MediaErrorCode;
import com.xuecheng.media.common.utils.AliyunVODUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
public class AliyunVoController implements AliyunVoApi {


    @Value("${aliyun.region}")
    private String region;

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;


    @PostMapping("/media/vod-token")
    @CrossOrigin //跨域
    public VodUploadToken createUploadToken(@RequestBody VodUploadRequest vodUploadRequest) {

        CreateUploadVideoResponse response = null;

        //访问外部资源，都要try/catch，不能用e.printStackTrace(),把异常信息写入日志中

        try {
            //初始化vod客户端
            DefaultAcsClient vodClient = AliyunVODUtil.initVodClient(region, accessKeyId, accessKeySecret);

            //创建请求
            response = AliyunVODUtil.createUploadVideo(vodClient, vodUploadRequest.getTitle(), vodUploadRequest.getFileName());
        } catch (Exception e) {

            log.error("阿里云vod调用出错,{}", e.getMessage());

            ExceptionCast.cast(MediaErrorCode.E_140012);
        }

        //解析响应,并赋值
        VodUploadToken token = new VodUploadToken();
        token.setVideoId(response.getVideoId());
        token.setUploadAddress(response.getUploadAddress());
        token.setUploadAuth(response.getUploadAuth());
        token.setRequestId(response.getRequestId());

        //响应给前端
        return token;
    }


    @GetMapping("/media/refresh-vod-token/{videoId}")
    public VodUploadToken refreshUploadToken(@PathVariable String videoId) {
        RefreshUploadVideoResponse response = null;

        try {
            //初始vod化客户端
            DefaultAcsClient vodClient = AliyunVODUtil.initVodClient(region, accessKeyId, accessKeySecret);

            //创建请求
            response = AliyunVODUtil.refreshUploadVideo(vodClient, videoId);
        } catch (Exception e) {

            log.error("阿里云VOD出错啦，{}", e.getMessage());

            ExceptionCast.cast(MediaErrorCode.E_140012);
        }

        //解析响应，并赋值
        VodUploadToken token = new VodUploadToken();
        token.setRequestId(response.getRequestId());
        token.setUploadAuth(response.getUploadAuth());
        token.setVideoId(response.getVideoId());
        token.setUploadAddress(response.getUploadAddress());

        //响应给前端
        return token;
    }
}
